package com.xiaodeng.xdblogspringboot.interceptors;



import cn.hutool.core.util.StrUtil;
import com.xiaodeng.xdblogspringboot.exception.UnauthorizedException;
import com.xiaodeng.xdblogspringboot.exception.UserException;
import com.xiaodeng.xdblogspringboot.exception.UserTokenException;
import com.xiaodeng.xdblogspringboot.utils.JwtUtil;
import com.xiaodeng.xdblogspringboot.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;

import static com.xiaodeng.xdblogspringboot.constant.RedisConstants.USER_TOKEN;


@Component
public class LoginInterceptor extends ServiceInterceptor {
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface GlobalJwtIntercept {
    }
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
  @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      HandlerMethod handlerMethod = (HandlerMethod) handler;
      GlobalJwtIntercept loginIntercept = handlerMethod.getMethod().getAnnotation(GlobalJwtIntercept.class);
      //如果要访问的方法上没有加这个注解，那么就说明这个方法不需要拦截，否则就需要进行拦截
      if (loginIntercept == null) return true;


      Object user = ThreadLocalUtil.get();
      System.out.println(user);
      if (user == null) {
          response.setStatus(401);
          return false;
      }
      return true;
    }


}
